package ask

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"

	"com.jiaguyu/dao/db"

	"com.jiaguyu/model"

	"com.jiaguyu/until"

	"com.jiaguyu/filter"
	"com.jiaguyu/id_gen"
	"com.jiaguyu/middleware/account"

	"com.jiaguyu/logger"
)

func QuestionSubmitHandle(ctx *gin.Context) {
	var question model.Question

	err := ctx.BindJSON(&question)

	if err != nil {
		until.ResponseError(ctx, until.ErrCodeParameter)
		return
	}

	//日志输入的地方
	fmt.Printf("参数问题%v\n", question)

	//敏感词的替换
	result, hit := filter.Replace(question.Caption, "###")
	if hit {
		until.ResponseError(ctx, until.ErrCodeCaptionHit)
		return
	}

	result, hit = filter.Replace(question.Content, "###")
	if hit {
		until.ResponseError(ctx, until.ErrCodeContentHit)
		return
	}
	fmt.Println(result)
	//获取question_id插入数据库
	qid, err := id_gen.GetId()
	fmt.Printf("qid:%v\n", qid)
	if err != nil {
		until.ResponseError(ctx, until.ErrCodeServerBusy)
		return
	}
	question.QuestionId = int64(qid)
	userId, err := account.GetUserId(ctx)
	fmt.Printf("userId:%d,err:%v\n", userId, err)
	if err != nil {
		until.ResponseError(ctx, until.ErrCodeNotLogin)
		return
	}

	question.AuthorId = userId

	err = db.CreateQuestion(&question)
	if err != nil {
		//日志打印
		until.ResponseError(ctx, until.ErrCodeServerBusy)
		return
	}
	until.ResponseSuccess(ctx, nil)
}

//获取详情问题详情
func GetQuestionListDetailHandle(ctx *gin.Context) {
	questionIdStr, ok := ctx.GetQuery("question_id")
	if !ok {
		until.ResponseError(ctx, until.ErrCodeParameter)
		logger.Error("参数错误:err=%V\n", ok)
		return
	}

	//将id转为int64
	questionId, err := strconv.ParseInt(questionIdStr, 10, 64)
	if err != nil {
		logger.Error("参数错误:err=%V,questionId:%V\n", err, questionId)
		until.ResponseError(ctx, until.ErrCodeParameter)
		return
	}
	question, err := db.GetQuestion(questionId)
	if err != nil {
		logger.Error("参数错误:err=%V\n", err)
		until.ResponseError(ctx, until.ErrCodeServerBusy)
		return
	}
	categoryMap, err := db.MGetCategoryList([]int64{question.CategoryId})
	if err != nil {
		logger.Error(":err=%V\n", err)
		until.ResponseError(ctx, until.ErrCodeServerBusy)
		return
	}

	category, ok := categoryMap[question.CategoryId]
	if !ok {
		logger.Error(":err=%V\n", err)
		until.ResponseError(ctx, until.ErrCodeServerBusy)
		return
	}
	//获取所有的userInfo数据
	userInfoList, err := db.GetUserInfoList([]int64{question.AuthorId})
	if err != nil || len(userInfoList) == 0 {
		logger.Error("获取用户信息失败")
		until.ResponseError(ctx, until.ErrCodeServerBusy)
		return
	}

	apiQuestionDetail := &model.ApiQuestionDetail{}
	apiQuestionDetail.Question = *question
	apiQuestionDetail.AuthorName = userInfoList[0].UserName
	apiQuestionDetail.CategoryName = category.CategoryName
	apiQuestionDetail.CreateTimeStr = apiQuestionDetail.CreateTime.Format("2006/1/2 15:04:05")

	until.ResponseSuccess(ctx, apiQuestionDetail)

	//根据questionId获取
}
